#include "gamestate.h"

GameState::GameState(QObject *parent)
    : QObject{parent}
{
    for (int i = 0; i < 9; ++i) {
        board.append("");
    }

    _stats["✕"] = 0;
    _stats["〇"] = 0;
}

QString GameState::stats() {
    return QString("✕ - %1 ...vs... 〇 - %2").arg(_stats["✕"]).arg(_stats["〇"]);
}

void GameState::dump_board() {
    qDebug() << board[0] << " " << board[1] << " " << board[2];
    qDebug() << board[3] << " " << board[4] << " " << board[5];
    qDebug() << board[6] << " " << board[7] << " " << board[8];
}

void GameState::place(int index) {
    board[index] = _turn;
    emit unitsChanged();

    check_board();

    _turn = _turn == "✕" ? "〇" : "✕";
    emit turnChanged();
}

void GameState::reset_board() {
    for (int i = 0; i < board.length(); ++i) {
        board[i] = "";
    }
    emit unitsChanged();
}

void GameState::check_board() {
    qDebug() << "check_board";

    static const int schemes[][3] = {
        0, 1, 2,
        3, 4, 5,
        6, 7, 8,
        0, 3, 6,
        1, 4, 7,
        2, 5, 8,
        0, 4, 8,
        2, 4, 6,
    };

    for (int i = 0; i < 8; ++i) {
        if (board[schemes[i][0]] != ""
            && board[schemes[i][0]] == board[schemes[i][1]]
            && board[schemes[i][1]] == board[schemes[i][2]]) {
            // qDebug() << _turn << "Win!";
            ++_stats[_turn];  // add point
            emit statsChanged();

            _win = true;
            emit winChanged();
        }
    }
}

void GameState::replay() {
    ++_round;
    emit roundChanged();

    // keep _turn

    _win = false;
    emit winChanged();

    dump_board();
    reset_board();
}
